const { Sequelize } = require('sequelize');
const logger = require('../utils/logger');

// 创建 Sequelize 实例
const sequelize = new Sequelize(
  process.env.DB_NAME || 'pet_nurse',
  process.env.DB_USER || 'root',
  process.env.DB_PASSWORD || '',
  {
    host: process.env.DB_HOST || 'localhost',
    port: process.env.DB_PORT || 3306,
    dialect: 'mysql',
    logging: (msg) => logger.debug(msg),
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    timezone: '+08:00',
    define: {
      timestamps: true,
      underscored: false,
      freezeTableName: true
    }
  }
);

const connectDB = async () => {
  try {
    await sequelize.authenticate();
    logger.info(`MySQL 连接成功: ${process.env.DB_HOST || 'localhost'}:${process.env.DB_PORT || 3306}`);
    
    // 同步数据库模型（开发环境）
    if (process.env.NODE_ENV === 'development') {
      try {
        // 使用 force: false 和 alter: false 避免意外删除表
        // 如果表不存在则创建，存在则不修改
        await sequelize.sync({ force: false, alter: false });
        logger.info('数据库模型同步成功');
      } catch (syncError) {
        logger.warn('数据库模型同步警告:', syncError.message);
        logger.info('将继续启动服务，但请检查数据库表结构');
      }
    }
    
  } catch (error) {
    logger.error('MySQL 连接失败:', error.message);
    logger.error('详细错误:', error);
    process.exit(1);
  }
};

module.exports = { sequelize, connectDB };